package com.ruoyi.web.controller.app;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.WxMiniAppLoginService;
import com.ruoyi.system.domain.vo.PaWxUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PaWxUser;

/**
 * 客户（小程序）Controller
 * 
 * @author ruoyi
 * @date 2024-07-11
 */
@RestController
@RequestMapping("/wx")
@Api(value = "微信小程序用户操作", tags = "微信小程序用户操作")
public class PaWxMiniAppUserController extends BaseController
{
    @Autowired
    private WxMiniAppLoginService wxMiniAppLoginService;



    @ApiOperation(value = "登录", notes = "登录")
    @GetMapping("/login")
    public R wxLogin(String code){
        if (StringUtils.isBlank(code)) {
            return R.fail("empty jscode");
        }
        PaWxUserVo login = wxMiniAppLoginService.login(code);
        return R.ok(login);
    }

    /**
     * 微信获取userId以后授权操作，保存用户信息
     */
    @Log(title = "客户（小程序）", businessType = BusinessType.INSERT)
    @PostMapping("/saveInfo")
    @ApiOperation(value = "保存用户信息", notes = "登录")
    public R saveInfo(@RequestBody PaWxUser paWxUser)
    {
        /*if (StringUtils.isBlank(paWxUser.getNickname()) || StringUtils.isBlank(paWxUser.getAvatarUrl())) {
            return R.fail("用户信息不能为空");
        }*/
        try {
            Long userId = getUserId();
            paWxUser.setWxUserId(userId);
            return wxMiniAppLoginService.saveInfo(paWxUser);
        } catch (Exception e) {
            return R.fail("授权有误");
        }
    }

    /**
     * 微信获取userId以后授权操作，保存用户信息
     */
    @Log(title = "获取手机号", businessType = BusinessType.INSERT)
    @GetMapping("/getPhone")
    @ApiOperation(value = "获取手机号", notes = "登录")
    public R<String> getPhone(String code)
    {
        try {
           String iphone = wxMiniAppLoginService.fetchPhoneInfo(code);
            return R.ok(iphone);
        } catch (Exception e) {
            return R.fail("授权有误");
        }
    }


}
